/**
 * Copyright (c) 2017-2024 Nop Platform. All rights reserved.
 * Author: canonical_entropy@163.com
 * Blog:   https://www.zhihu.com/people/canonical-entropy
 * Gitee:  https://gitee.com/canonical-entropy/nop-entropy
 * Github: https://github.com/entropy-cloud/nop-entropy
 */
package com.gitee.wsl.prop

class PropPath(val name: String, val next: PropPath? = null){

    var fullName: String? = null
        get() {
            if (next == null) return name

            if (field == null) {
                val sb = StringBuilder()
                getFullName(sb)
                field = sb.toString()
            }
            return field
        }
        private set

    override fun hashCode(): Int {
        return toString().hashCode()
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true

        if (other !is PropPath) return false

        return fullName == other.fullName
    }

    override fun toString(): String {
        return fullName!!
    }

    fun getFullName(sb: StringBuilder) {
        sb.append(name)
        if (next != null) {
            sb.append('.')
            next.getFullName(sb)
        }
    }

    val owner: PropPath?
        get() {
            if (next == null) return null
            return PropPath(name, next.owner)
        }

    val last: String
        get() {
            if (next == null) return name
            return next.last
        }

    companion object {
        fun parse(str: String): PropPath {
            val pos = str.indexOf('.')
            if (pos < 0) {
                return PropPath(str, null)
            }
            return PropPath(str.substring(0, pos), parse(str.substring(pos + 1)))
        }
    }
}